https://discord.gg/botpress logo
Dynamic Carousel error
# 🤝help
g
Hi to All, I am developing a restaurant bot and have more than 150 menu items, I have the output regarding the query of customers' choice. Customer is looking for milk shake options. Suppose there are 5 options in milk shake category. I am getting the result in the format as below: this is store in a variable 'workflow.carouselItems' of object datatype. First execute card has this code const myDict = { "type": "carousel", "items": [ { "title": "Strawberry Milkshake", "subtitle": "Strawberry milkshake - £5.5", "image_url": "https://myimage.jpg/" }, { "title": "Banana Milkshake", "subtitle": "Banana milkshake - £5.5", "image_url": "https://myimage.jpg/" }, { "title": "Oreo Milkshake", "subtitle": "Oreo milkshake - £5.5", "image_url": "https://myimage.jpg/" }, { "title": "Kinder Milkshake", "subtitle": "Kinder milkshake - £5.5", "image_url": "https://myimage.jpg" }, { "title": "Caramel Milkshake", "subtitle": "Caramel milkshake - £5.5", "image_url": "https://myimage.jpg/" } ] } workflow.tempObj = myDict; == https://cdn.discordapp.com/attachments/1409383414041149511/1409383414741864448/image.png?ex=68ad2e17&is=68abdc97&hm=8abe0dec411d8fb30a892cba74139cf4e71c96e6be5b904034173b0564c05d5e&
The second execute card has the code as below: // Input: workflow.tempObj (my mimic dict) const obj = workflow.tempObj || {}; const items = Array.isArray(obj.items) ? obj.items : []; // 1) No-result if (items.length === 0) { workflow.noResultMessage = `No match for “${(event.preview || event.payload?.text || '').trim()}”. Try Pizza / Burgers / Desserts.`; workflow.carouselItems = []; // fallback could be top sellers workflow.showTopSellers = true; return; } // 2) Over-result cap (limit to 10) let over = false; let filtered = items; if (items.length > 10) { over = true; filtered = items.slice(0, 10); } workflow.overResultMessage = over ? 'Showing top 10. Want me to narrow it by price, diet, or category?' : null; // 3) Normalize for Botpress carousel workflow.carouselItems = filtered.map((r, idx) => { const title = r.title || `Item ${idx+1}`; const subtitle = r.subtitle || ''; const imageUrl = r.imageUrl || r.imageUrl || null; // Postback action with stable id (here just index since mimic data has no id) const actions = [ { action: 'Postback', label: 'Add to order', value: JSON.stringify({ action:'add', sku: title }) } ]; return { title, subtitle, imageUrl, actions }; }); === I have tried to access these in carousel card manually by creating 10 cards upto index 9, I can by {{workflow.carouselItems[0].title}} {{workflow.carouselItems[0].subtitle}} {{workflow.carouselItems[0].imageUrl}} and by changing the index number for each. But as you know, the number of items in the record can be of any size, so creating the carousel cards in it is a big pain for me at the moment. Please help me in this. Thank You in advance
l
create the carousel using execute code card so that you do not have to write it like this - may i know where is the data stored
g
I am using google sheet API to retrieve data from Gsheets
How to create the carousel using execute code card? Any reference to the directory?
l
> `const SPREADSHEET_ID = ''; > const RANGE = 'Menu!A2:C'; <- your sheet range > const API_KEY = 'API Key'; <- your api key > > const url = `https://sheets.googleapis.com/v4/spreadsheets/${SPREADSHEET_ID}/values/${RANGE}?key=${API_KEY}`; > const res = await fetch(url); > const json = await res.json(); > > if (!json.values) { > throw new Error('No data found in sheet'); > } > > const carouselItems = json.values.map(([title, subtitle, imageUrl]) => ({ > type: 'carousel', > title, > subtitle, > image_url: imageUrl?.trim() > })); > > workflow.carouselItems = carouselItems;`
try this and improvise
g
Ok, thank you so much. Let me try 😇
Hi @limited-pencil-78283 , I have tried the code you mentioned, the process being done in this code, I have already implemented this. The problem is, I cant display the results in carousel dynamically. For this single result, I hard-coded the fields of carousel card by index as shown in the screenshot. How to generate the carousel dynamically, so that everytime the carousel cards initiate equals to the number of results / length in 'workflow.carouselItems'. Thank you in advance for your help and guidance. https://cdn.discordapp.com/attachments/1409383414041149511/1409625524958924872/image.png?ex=68ae0f92&is=68acbe12&hm=28360c69589653255ae9ea2b335455401df28a23e1e8a19fb59033c5bc650ba3& https://cdn.discordapp.com/attachments/1409383414041149511/1409625525298659338/image.png?ex=68ae0f92&is=68acbe12&hm=04edbef721a0732cd6a7324047562bb48d76d38057ad104cef14178ae610f2fc& https://cdn.discordapp.com/attachments/1409383414041149511/1409625525642858598/image.png?ex=68ae0f92&is=68acbe12&hm=86ece47cfeff042817484ded44462f33b6993e38607e16d9f4a280a1147edcab&
l
Copy code
const SPREADSHEET_ID = '<spread sheet id>';
const RANGE = 'Menu!A2:C';
const API_KEY = 'API Key';

const url = `https://sheets.googleapis.com/v4/spreadsheets/${SPREADSHEET_ID}/values/${RANGE}?key=${API_KEY}`;
const res = await fetch(url);
const json = await res.json();

if (!json.values) {
  throw new Error('No data found in sheet');
}

const products = json.values.map(([propertyName, price, image]) => ({
  propertyName: propertyName?.trim(),
  price: price?.trim(),
  image: image?.trim(),
  link: image?.trim()
}));

await client.createMessage({
  userId: event.botId,
  conversationId: event.conversationId,
  tags: {},
  type: 'carousel',
  payload: {
    type: 'carousel',
    items: products.map((product) => ({
      type: 'card',
      title: product.propertyName,
      subtitle: product.price,
      imageUrl: product.image,
      actions: [
        {
          label: 'View Product',
          value: product.link,
          action: 'url'
        }
      ]
    }))
  }
});
can you try this
send this via the execute code card and not the carousel card
g
// Example cards array (make yours dynamically) const cards = [ { type: 'card', title: 'Strawberry Milkshake', subtitle: '£5.5', imageUrl: 'https://picsum.photos/300', actions: [ { action: 'postback', label: 'Add to Cart', value: JSON.stringify({ action: 'add', sku: 'Strawberry Milkshake' }) } ] }, { type: 'card', title: 'Banana Milkshake', subtitle: '£5.5', imageUrl: 'https://picsum.photos/301', actions: [ { action: 'postback', label: 'Add to Cart', value: JSON.stringify({ action: 'add', sku: 'Banana Milkshake' }) } ] } ] // Execute Code card const url = 'https://api.botpress.cloud/v1/chat/messages' const body = { userId: event.userId, // the human you’re chatting with conversationId: event.conversationId, // the active conversation type: 'carousel', payload: { type: 'carousel', items: cards } } const res = await fetch(url, { method: 'POST', headers: { 'Authorization':
Bearer ${'my personal access token'}
, 'x-bot-id': 'my bot id', 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) if (!res.ok) { const text = await res.text().catch(() => '') throw new Error(
Runtime API failed ${res.status}: ${text}
) } I have tried multiple ways, and recently i have tried this one but all in vain. The error I am getting is Error executing action "inline-card:"Dynamic Carousel Display for Milkshake Menu Options".js" in flow:MenuWorkflow:node:Standard6 [Error, Runtime API failed 400: {"id":"c81685bb102b222cb0fcc0d194ffb268","code":400,"type":"InvalidPayload","message":"request/body must have required property 'tags', request/body/userId must NOT have fewer than 28 characters, request/body/conversationId must NOT have fewer than 28 characters"} but i don't know where to get userId and conversationId. One way is to use event.botId and event.conversationId, but not working
l
but i don't know where to get userId and conversationId. -> event.userId and event.conversationId
g
This is not working. I tried this.
l
Copy code
const properties = [
  {
    propertyName: 'Villa Aurora',
    price: '$750,000',
    image: 'https://www.roofandfloor.com/project/1658/gallery/Casagrand_Boulevard_1.jpg',
    link: 'https://www.roofandfloor.com/bengaluru/project/casagrand-boulevard-in-hennur-road/1658'
  },
  {
    propertyName: 'Oceanview Estate',
    price: '$1,200,000',
    image: 'https://www.roofandfloor.com/project/2911/gallery/Casagrand_Zaiden_1.jpg',
    link: 'https://www.roofandfloor.com/bengaluru/project/casagrand-zaiden-in-talaghattapura/2911'
  },
  {
    propertyName: 'Mountain Retreat',
    price: '$620,000',
    image: 'https://www.roofandfloor.com/project/2729/gallery/GVS_Habitat_1.jpg',
    link: 'https://www.roofandfloor.com/bengaluru/project/gvs-habitat-in-babusa-palya/2729'
  },
  {
    propertyName: 'City Lights Condo',
    price: '$480,000',
    image: 'https://www.roofandfloor.com/project/2678/gallery/VA_Serenity_1.jpg',
    link: 'https://www.roofandfloor.com/bengaluru/project/va-serenity-in-nelamangala/2678'
  },
  {
    propertyName: 'Lakeside Bungalow',
    price: '$530,000',
    image: 'https://www.roofandfloor.com/project/2676/gallery/VA_Purity_1.jpg',
    link: 'https://www.roofandfloor.com/bengaluru/project/va-purity-in-sondekoppa-road/2676'
  }
]

// Construct carousel items
const carouselItems = properties.map((product) => {
  return {
    type: 'card',
    title: {
      dynamicValue: product.propertyName,
      valueType: 'dynamic'
    },
    imageUrl: {
      dynamicValue: `${product.image}`,
      valueType: 'dynamic'
    },
    actions: [
      {
        action: 'postback',
        label: {
          dynamicValue: 'Open',
          valueType: 'dynamic'
        },
        value: {
          dynamicValue: `${product.link}`,
          valueType: 'dynamic'
        }
      }
    ]
  }
})

bp.dm.replyToEvent(event, {
  type: 'carousel',
  items: carouselItems
})
https://cdn.discordapp.com/attachments/1409383414041149511/1413233969763320019/image.png?ex=68bb3033&is=68b9deb3&hm=921716e9d94ced33c6141fa92f59b5c0e3f98088dd59ce6f3e7d5b866a60a7c2& https://cdn.discordapp.com/attachments/1409383414041149511/1413233970413305866/image.png?ex=68bb3033&is=68b9deb3&hm=eb760f1e9f017be59bbef34ca27a83f8d7247356b30815ef74f2918a7e92b607&
g
Great 😃👍 I guess this should work for me too. I am going to give it a try now. 😃😄😇 Thank you soo much.
Thank you soo much, this is working. But, the action button is not working. How both action buttons are supposed to work, postback and open URL actions??
For example,If I want to run a 'Add to Cart' functionality from this action button. It will be a great favor. Thank You in advance
to show "Add to Cart" change actions: [ { action: 'postback', label: { dynamicValue: 'Add to Cart', <- value here valueType: 'dynamic' }, value: { dynamicValue:
${product.link}
, valueType: 'dynamic' } } ] https://cdn.discordapp.com/attachments/1409383414041149511/1413778578302173244/image.png?ex=68bd2b67&is=68bbd9e7&hm=52e8d996bc3fc18d8e8718bd6a6b304269eb95c7566f2f3f97dec1ced071744f&
g
Okk... Thank you so much again 😊😊 alot of best wishes for you
6 Views